<template>
  <div>
    <n-card :bordered="false">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="mt-3">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row:ListData) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :striped="true"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新建
          </n-button>
        </template>

        <template #toolbar> </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="名称" path="title">
          <n-input placeholder="请输入名称" v-model:value="formParams.title" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, unref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { columns, ListData } from './types';
  import { PlusOutlined } from '@vicons/antd';
  import { deleteType, getType, patchType, putType } from '@/api/type/type';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useDialog } from 'naive-ui';
  import { FormRules } from 'naive-ui/lib';
  const dialog = useDialog();
  const showModal = ref(false);
  const formRef: any = ref(null);
  const formBtnLoading = ref(false);
  const defaultValueRef = () => ({
    id: 0,
    title: '',
    model: 'Course',
  });

  let formParams = reactive(defaultValueRef());

  const rules: FormRules = {
    name: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入名称',
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'title',
      component: 'NInput',
      label: '分类名称',
      rules: [{ required: true, message: '请输入分类名称', trigger: ['blur'] }],
    },
  ];

  const actionRef = ref();

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            // auth: ['basic_list'],
          },
        ],
        select: (key: any) => {
          window['$message'].info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  function addTable() {
    formParams = Object.assign(unref(formParams), defaultValueRef());
    showModal.value = true;
  }

  const loadDataTable = async (res) => {
    res.model = 'Course';
    const response: any = await getType({ ...getFieldsValue(), ...res });
    return {
      list: response.data, // 映射数据列表
      page: response.page, // 映射当前页码
      pageSize: response.pageSize, // 映射每页大小
      itemCount: response.total, // 映射总记录数
    };
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function handleEdit(record: Recordable) {
    formParams.id = record.id;
    formParams.title = record.title;
    showModal.value = true;
  }

  function handleDelete(record: Recordable) {
    dialog.warning({
      title: '删除操作',
      content: '你确定删除这个课程么',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const response: any = await deleteType(record.id);
        if (response.code === ResultEnum.SUCCESS) {
          actionRef.value.reload();
        }
      },
    });
  }

  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        let response: any = null;
        if (formParams.id) {
          response = await patchType(formParams);
        } else {
          response = await putType(formParams);
        }
        if (response.code === ResultEnum.SUCCESS) {
          Object.assign(formParams, response.data);
          showModal.value = false;
          reloadTable();
        }
      } else {
        window['$message'].error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }
</script>

<style lang="less" scoped></style>
